#-*- coding: utf-8 -*-

from django.http import HttpResponse, HttpResponseRedirect
from django.db import transaction
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from django.contrib import messages
from django.contrib.auth import login, logout, authenticate
from django.contrib.auth.models import User
from django.views.generic import TemplateView, View
from django.views.generic.edit import FormView
from models import Account
from forms import SigninForm, SignupForm
from utils import generate_username, generate_active_token, send_active_token, send_active_token_async


class SigninView(FormView):
    """ 登录视图
    template_name: 视图渲染模版
    form_class: 登录表单form类
    from_valid: 表单验证通过执行的方法
    """
    template_name = 'account/signin.html'
    form_class = SigninForm
    #success_url = '/account/home'

    def form_valid(self, form):
        # post数据验证通过
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            # 认证用户
            user = authenticate(username=username, password=password)
            if user is not None:
                # 用户是否注销
                if user.is_active:
                    # 登入系统
                    login(self.request, user)
                    messages.success(self.request, u'登入成功')
                    return redirect(reverse('home'))
                else:
                    messages.warning(self.request, u'用户注销了')
                    return redirect(reverse('signin'))
            else:
                messages.warning(self.request, u'用户名或密码错误')
                return redirect(reverse('signin'))
        return super(SigninView, self).form_valid(form)


class SignupView(FormView):
    """ 注册视图
    template_name: 视图渲染模版
    form_class: 注册表单form类
    from_valid: 表单验证通过执行的方法
    """
    template_name = 'account/signup.html'
    form_class = SignupForm

    def form_valid(self, form):
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']

        # 判断用户名类型，返回 email 或者 phone
        identifier_type = form.cleaned_data['identifier_type']
        is_send_email = False
        try:
            # 注册事务，先创建user，然后创建account
            with transaction.atomic():
                user = User()
                user.username = generate_username(username)
                user.set_password(password)
                user.save()

                if identifier_type == 'email':
                    user.email = username
                    user.save()
                    account = Account(user=user)
                    active_token = generate_active_token(username)
                    account.active_token = active_token
                    account.save()
                    # todo
                    # 注册成功，发送验证邮件。发送 email 会阻塞，以后改用 celery 任务队列， 异步（async）发送
                    #send_active_token(host=self.request.get_host(), to_email=username, active_token=active_token)
                    send_active_token_async(host=self.request.get_host(), to_email=username, active_token=active_token)
                else:
                    account = Account(user=user)
                    account.phone = username
                    account.save()

                messages.success(self.request, u'注册成功！，请登录邮箱查看激活邮件，重新发送邮件')
                return redirect(reverse('signin'))
        except Exception, e:
            raise e
            messages.warning(self.request, u'注册失败！')
        return redirect(reverse('signup'))


class SignoutView(View):
    """ 登出视图 """
    def get(self, request):
        logout(request)
        messages.info(request, u'退出成功')
        return HttpResponseRedirect(reverse('index'))

class HomeView(TemplateView):
    template_name = 'account/home.html'

    def get_context_data(self):
        pass
